function $(nodeName) {
	return document.getElementsByName(nodeName);
};
var designClass = "design_class", hideClass = "hide_class", browseClass = "browse_class", addClass = "add_class", editClass = "edit_class";
var upWindow = window.parent.frames["zwIframe"];
if (!upWindow) {
	upWindow = window.parent.frames["componentDiv"].frames["zwIframe"];
}
// 关闭自定义扩张控件弹出窗口
function fy_dialog_close() {
	window.parent.$(".layui-layer-iframe").parent().find(".layui-layer-close").trigger(
			"click");
}

function getUpFields(name) {
	return upWindow.$("[validate*='name:\"" + name + "\"']");
}

function getUpFieldsByFieldval(name) {
	return upWindow.$("[fieldval*='displayName:\"" + name + "\"']");
}
function getUpAccountFieldValue(name) {
	var field = getUpFields(name).eq(0);
	return {
		displayValue : field.is("span") ? field.text() : field.val(),
		value : eval("(" + field.parent("span").attr("fieldVal") + ")").value
	};
}

function getUpFieldValueByName(name, index) {
	return getUpFieldValue(getUpFieldsByFieldval(name).eq(index ? index : 0));
}

function getUpFieldValue(field) {
	var fieldVal = field.attr("fieldVal");
	var editTag = field.hasClass(editClass);
	var browseTag = field.hasClass(browseClass);
	var addTag = field.hasClass(addClass);
	if (fieldVal != null && typeof (fieldVal) != 'undefined') {
		fieldVal = eval("(" + fieldVal + ")");
	} else {
		return null;
	}
	var obj = new Object();
	obj.displayName = fieldVal.displayName;
	obj.name = fieldVal.name;
	var tag = true;
	switch (fieldVal.inputType) {
	case "text":
	case "textarea":

		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "checkbox":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		}
		break;
	case "radio":
		if (editTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find(":radio:checked").attr("val4cal");
		}
		break;
	case "select":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + " option:selected")
					.attr("val4cal");
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).attr("val4cal");
		}
		break;
	case "date":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
			if (obj.value != "") {
				obj.value = obj.value + " 00:00";
			}
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "datetime":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "flowdealoption":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		} else if (addTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "lable":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relationform":
		if (editTag) {
			obj.value = fieldVal.value;
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "relation":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "project":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name).val();
		} else if (browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "member":
	case "multimember":
	case "account":
	case "multiaccount":
	case "department":
	case "multidepartment":
	case "post":
	case "multipost":
	case "level":
	case "multilevel":
		if (editTag) {
			obj.value = field.find("#" + fieldVal.name + "_txt").val();
		} else if (browseTag) {
			obj.value = field.find("#" + fieldVal.name).text();
		}
		break;
	case "attachment":
	case "image":
	case "document":
		if (editTag || browseTag) {
			var attNames = "";
			var tempField = field.find("#" + fieldVal.name);
			var tempFileId = "";
			if (tempField[0].tagName.toLowerCase() == "input") {
				tempFileId = tempField.val();
			} else if (tempField[0].tagName.toLowerCase() == "span") {
				tempFileId = tempField[0].innerHTML;
			}
			var atts = upWindow.getAttBySubreference(tempFileId);
			for ( var j = 0; j < atts.length; j++) {
				attNames += atts[j].filename + ",";
			}
			if (attNames != "") {
				attNames = attNames.substr(0, attNames.length - 1);
			}
			obj.value = attNames;
		}
		break;
	case "outwrite":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "externalwrite-ahead":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "exchangetask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	case "querytask":
		if (editTag || browseTag) {
			obj.value = fieldVal.value;
		}
		break;
	default:
		tag = false;
	}
	if (obj.value != undefined) {
		obj.value = obj.value.replace("\r\n", ";");
		obj.value = obj.value.replace("\n", ";");
	}
	return obj;
}

function setUpFieldValue(name, value) {
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input").val(
			value);
	upWindow.$("[fieldval*='displayName:\"" + name + "\"']").find("input")
			.trigger("blur");
}

function setUpFieldValue2(field, value, displayValue, index) {

	try {

		var fieldVal = field.attr("fieldVal");
		var editTag = field.hasClass(editClass);
		var addTag = field.hasClass(addClass);
		value = (value);
		displayValue = displayValue ? (displayValue) : displayValue;
		if (fieldVal != null && typeof (fieldVal) != 'undefined') {
			fieldVal = eval("(" + fieldVal + ")");
		} else {
			return null;
		}
		var tag = true;
		switch (fieldVal.inputType) {
		case "text":
		case "textarea":
			if (editTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			} else if (addTag) {
				var inField = field.find("#" + fieldVal.name);
				inField.val(value);
				inField.trigger("blur");
			}
			break;
		case "checkbox":
			if (editTag) {
				field.find("#" + fieldVal.name).attr("checked", true);
				field.find("#" + fieldVal.name).trigger("click");
			}
			break;
		case "radio":
			if (editTag) {
				field.find(":radio").eq(index).attr("checked", true);
				field.find(":radio").eq(index).trigger("click");
			}
			break;
		case "select":
			if (editTag) {
				var options = field.find("#" + fieldVal.name + " option");
				for ( var k = 0; k < options.length; k++) {
					if (options.eq(k).text() == value)
						options.eq(k).attr("selected", true);
				}
				field.find("#" + fieldVal.name).trigger("change");
			}
			break;
		case "date":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "datetime":
			if (editTag) {
				field.find("#" + fieldVal.name).val(value);
				field.find("#" + fieldVal.name).trigger("blur");
			}
			break;
		case "member":
		case "multimember":
		case "account":
		case "multiaccount":
		case "department":
		case "multidepartment":
		case "post":
		case "multipost":
		case "level":
		case "multilevel":
			if (editTag) {
				alert(editTag);
				field.find("#" + fieldVal.name + "_txt").val(value);
			}
			break;
		}
	} catch (e) {
		// TODO: handle exception
	}
}
// 添加或者删除行
function addOrDelRepeat(name, newLength) {
	var fields = getUpFieldsByFieldval(name);
	var oldLength = fields.length;
	var tbody = getUpFieldsByFieldval(name).eq(0).parent();
	while (!tbody.is("tbody")) {
		tbody = tbody.parent();
	}
	for ( var i = 0, length = Math.abs(newLength - oldLength); i < length; i++) {
		if (newLength > oldLength) {
			upWindow.fy_addEmpty(tbody.children().last());
		} else {
			upWindow.fy_delCurrentRepeat(tbody.children().last());
		}
	}
}
var companyMap = {
	"福耀玻璃" : "01",
	"万达公司" : "02",
	"长春轿车" : "04",
	"重庆配件公司" : "05",
	"上海轿车" : "06",
	"机械制造" : "07",
	"北京公司" : "11",
	"通辽公司" : "12",
	"长春巴士" : "13",
	"重庆公司（新区）" : "14",
	"广州福耀" : "18",
	"包边公司" : "19",
	"集团总办" : "20",
	"大巴公司" : "26",
	"上海客车" : "27",
	"湖北公司" : "30",
	"郑州福耀" : "40",
	"广东佛山" : "42",
	"成都绿榕" : "45",
	"沈阳福耀" : "43",
	"烟台福耀" : "46",
	"福州福耀模具" : "47",
	"工程玻璃" : "a10",
	"福清汽配" : "a11",
	"福清浮法" : "a12",
	"万盛浮法" : "a13",
	"通辽浮法" : "a14",
	"双辽浮法" : "a15",
	"武汉福耀" : "49",
	"保定福耀" : "50",
	"天津福耀" : "52"
}

var typeMap = {
	'成本中心段' : '0',
	'科目段' : '1',
	'子科目段' : '2',
	'分类' : '3',
	'内部往来' : '4',
	'备注' : '5'
};

var fieldMap = {
	'companySelect' : '公司',
	'typeSelect' : '段别',
	'code' : '科目代码',
	'subjectNumber' : '项目令号',
	'remark' : '科目说明'
};

var notAllowBlankFields = [ 'companySelect', 'typeSelect', 'code', 'remark' ];

function createShowSubjectInfoTableRow(row) {
	var tr = document.createElement("tr");
	tr.name = "showSubjectInfoTR";
	tr.valign = "middle";
	var td1 = document.createElement("td");
	td1.innerText = row.code;
	tr.appendChild(td1);
	var td2 = document.createElement("td");
	td2.innerText = row.name;
	tr.appendChild(td2);
	// var td3 = document.createElement("td");
	// td3.innerText = !row.cost ? "" : row.cost;
	// tr.appendChild(td3);
	var td4 = document.createElement("td");
	td4.innerText = row.time.split(" ")[0];
	tr.appendChild(td4);
	var td5 = document.createElement("td");
	var aNode = document.createElement("a");
	aNode.style.color = 'red';
	aNode.href = 'javascript:void(0)';
	aNode.onclick = retrunValue;
	aNode.innerHTML = "选择<input style='display:none;' value='" + row.code
			+ "'/>";
	td5.appendChild(aNode);
	tr.appendChild(td5);
	document.getElementById("showSubjectInfoTBody").appendChild(tr);
}

function removeShowSubjectInfoTableRow() {
	// var children =
	// document.getElementById("showSubjectInfoTable").childNodes;
	// for (var i = 0; i < children.length; i++) {
	// if (children[i].name == 'showSubjectInfoTR')
	// document.getElementById("showSubjectInfoTable")
	// .removeChild(children[i]);
	// }
	while (document.getElementById("showSubjectInfoTBody").hasChildNodes()) {
		document.getElementById("showSubjectInfoTBody").removeChild(
				document.getElementById("showSubjectInfoTBody").lastChild);
	}
}

function _ajax(url, operator) {

	var xmlhttp = null;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	document.getElementById("lodingDiv").style.display = '';
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				text = xmlhttp.responseText;
				if (text == 1) {
					alert("用户还未登陆，或者已掉线");
				} else if (text == 2) {
					alert("参数不能为空。");
				} else {
					operator(text);
				}
			} else {
				alert("连接服务器异常");
			}
			document.getElementById("lodingDiv").style.display = 'none';
		}
	};
	xmlhttp.open("get", url, true);
	xmlhttp.send();
}

/**
 * 单击确定按钮，将数据回写到表单
 */
function onOKButtonClick() {

	var _size = $(notAllowBlankFields[0]).length;
	for ( var m = 0; m < _size; m++) {
		for ( var i = 0; i < notAllowBlankFields.length; i++) {
			var field = $(notAllowBlankFields[i])[m];
			if (notAllowBlankFields[i] == "code") {
				if (field.value.indexOf('3') == 0
						|| field.value.indexOf('4') == 0) {
					var subjectNumberField = $("subjectNumber")[m];
					if ($("typeSelect")[m].value == '2'
							&& (!subjectNumberField.value || subjectNumberField.value == "")) {
						alert("第" + (m + 1) + "行，"
								+ fieldMap["subjectNumber"].replace('', '')
								+ "字段不能为空");
						return;
					}
				}
			}
			if (field.readOnly == false && (!field.value || field.value == "")) {
				alert("第" + (m + 1) + "行，"
						+ fieldMap[notAllowBlankFields[i]].replace('', '')
						+ "字段不能为空");
				return;
			}
		}
	}

	for ( var i = 0; i < notAllowBlankFields.length; i++) {
		var fields = $(notAllowBlankFields[i]);
		for ( var j = 0; j < fields.length; j++) {
			if (fields[j].readOnly == false
					&& (!fields[j].value || fields[j].value == "")) {
				alert("第" + (j + 1) + "行，"
						+ fieldMap[notAllowBlankFields[i]].replace('', '')
						+ "字段不能为空");
				return;
			}
		}
	}

	var companyNodes = $('companySelect');

	// var oldLength = getUpFieldsByFieldval(fieldMap.companySelect).length;

	addOrDelRepeat(fieldMap.companySelect, companyNodes.length);

	// var upTR = getParentTR($2(fieldMap.companySelect)[oldLength - 1]);
	// for ( var i = 0; i < companyNodes.length; i++) {
	// upTR.id = "oper";
	// window.dialogArguments.addEmpty();
	// }
	//
	// for ( var i = 0; i < oldLength; i++) {
	// getParentTR($2(fieldMap.companySelect)[0]).id = "oper";
	// window.dialogArguments.del();
	// }
	setUpFieldValue2(getUpFieldsByFieldval("是否用友ERP").eq(0), 1);
	setUpFieldValue2(getUpFieldsByFieldval("是否含子科目段").eq(0), 1);

	for ( var i = 0; i < companyNodes.length; i++) {
		if (companyNodes[i].value.indexOf("a") == -1) {
			setUpFieldValue2(getUpFieldsByFieldval("是否用友ERP").eq(0), 0);
		}
		// 判断是否包含不是子科目段和成本中心段的字段
		if ($('typeSelect')[i].value != '2' && $('typeSelect')[i].value != '0') {
			setUpFieldValue2(getUpFieldsByFieldval("是否含子科目段").eq(0), 0);
		}
		setUpFieldValue2(getUpFieldsByFieldval(fieldMap.subjectNumber).eq(i),
				$('subjectNumber')[i].value);
		setUpFieldValue2(
				getUpFieldsByFieldval(fieldMap.companySelect).eq(i),
				$('companySelect')[i].options[$('companySelect')[i].selectedIndex].text);
		setUpFieldValue2(
				getUpFieldsByFieldval(fieldMap.typeSelect).eq(i),
				$('typeSelect')[i].options[$('typeSelect')[i].selectedIndex].text);
		setUpFieldValue2(getUpFieldsByFieldval(fieldMap.remark).eq(i),
				$('remark')[i].value);
		setUpFieldValue2(getUpFieldsByFieldval(fieldMap.code).eq(i),
				$('code')[i].value);
	}

	// alert($2("是否含子科目段")[0].value);
	fy_dialog_close();
}
/**
 * 科目段更改
 * 
 * @param {}
 *            node
 */
function onTypeChange(node) {
	var typeNodes = $(node.name);
	for ( var i = 0; i < typeNodes.length; i++) {
		if (typeNodes[i] == node) {
			if (node.value == '2') {
				$('subjectNumber')[i].readOnly = true;
				$('subjectNumber')[i].className = 'fill';
				$('subjectNumber')[i].value = "";
				$('queryImg')[i].style.display = '';
				// checkCode($('code')[i]);
			} else {
				$('subjectNumber')[i].readOnly = true;
				$('subjectNumber')[i].className = 'readonly';
				$('subjectNumber')[i].value = "";
				$('queryImg')[i].style.display = 'none';
			}
			break;
		}
	}
}
/**
 * 填写项目令号
 * 
 * @param {}
 *            dom
 */
function onQuerySubjectCodeImgClick(dom) {
	document.getElementById("querySubjectDiv").style.display = '';
	dom.id = 'operateImage';
	document.getElementById("fillSubjectTable").style.display = "none";
}
function hideDiv() {
	removeShowSubjectInfoTableRow();
	document.getElementById("querySubjectDiv").style.display = 'none';
	document.getElementById("operateImage").id = "";
	document.getElementById("fillSubjectTable").style.display = "";
}
function querySubjectInfo(button) {
	var operate;
	var field;
	if (button.id == "querySubjectCodeButton") {
		operate = 1;
		field = document.getElementById("querySubjectCodeInput").value;
	} else if (button.id == "querySubjectNameButton") {
		operate = 2;
		field = document.getElementById("querySubjectNameInput").value;
	} else {
		alert("界面操作异常");
		return;
	}
	if (field.length < 4) {
		alert("请至少输入4个汉字或者符号");
		return;
	}
	removeShowSubjectInfoTableRow();
	_ajax('../../erp2oaController.do?method=querySubjectInfo&field='
			+ encodeURIComponent(encodeURIComponent(field)) + "&operate="
			+ operate, function(text) {
		var obj = eval('(' + text + ')');
		if (obj.success) {
			var result = obj.result;
			for ( var i = 0; i < result.length; i++) {
				createShowSubjectInfoTableRow(result[i]);
			}
		} else {
			alert(obj.result);
		}
	});
}
function retrunValue() {
	var code = this.lastChild.value;
	var imgDoms = $('queryImg');
	for ( var i = 0; i < imgDoms.length; i++) {
		if (imgDoms[i].id == "operateImage") {
			$("subjectNumber")[i].value = code;
			break;
		}
	}
	hideDiv();
	return false;
}

// function checkCode(codeInput) {
// // var codes = $('code');
// // for ( var i = 0; i < codes.length; i++) {
// // if (codeInput = codes[i]) {
// // if ($('typeSelect')[i].value == '2') {
// // if (codeInput.value.indexOf('1') == 0
// // || codeInput.value.indexOf('2') == 0) {
// // codeInput.value = codeInput.value.replace('1', '');
// // codeInput.value = codeInput.value.replace('2', '');
// // alert('子科目段的科目代码第一位不能为1或2');
// // while (codeInput.value.indexOf('1') == 0
// // || codeInput.value.indexOf('2') == 0) {
// // codeInput.value = codeInput.value.replace('1', '');
// // codeInput.value = codeInput.value.replace('2', '');
// // }
// //
// // }
// // }
// // break;
// // }
// // }
// }
function createOption(msg,key){
	var op = document.createElement("option");
	op.value = key;
	op.text = msg;
	return op;
}
window.onload = function() {
	// _ajax(
	// '../../../erp2oaController.do?method=getCompanyJSON',
	// function(text) {
	// companyMap = eval('(' + text + ')');
	$('companySelect')[0].options.add(createOption("", ""));
	var op = document.createElement("option")
	op.text = "";
	op.value = "";
	$('companySelect')[0].options.add(op);
	op = null;
	for ( var key in companyMap) {
		op = document.createElement("option")
		op.text = key;
		op.value = companyMap[key];
		$('companySelect')[0].options.add(op);
		op = null;
//		$('companySelect')[0].options.add(createOption(key, companyMap[key]));
	}
	$('companySelect')[0].value = "";

	$('typeSelect')[0].options.add(createOption("", ""));
	for ( var key in typeMap) {
		$('typeSelect')[0].options.add(createOption(key, typeMap[key]));
	}
	$('typeSelect')[0].value = "";

	var firstTR = getParentTR($('companySelect')[0]);
	var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
	repeatOperator.addListeners(firstTR);

	var upTypeNodes = getUpFieldsByFieldval(fieldMap.typeSelect);
	repeatOperator.addEmptyTR(firstTR, upTypeNodes.length - 1);

	for ( var i = 0; i < upTypeNodes.length; i++) {
		if (getUpFieldValue(upTypeNodes.eq(i)).value == '子科目段') {
			$('subjectNumber')[i].readOnly = true;
			$('subjectNumber')[i].className = 'fill';
			$('subjectNumber')[i].value = "";
			$('queryImg')[i].style.display = '';
			// checkCode($('code')[i]);
		} else {
			$('subjectNumber')[i].readOnly = true;
			$('subjectNumber')[i].className = 'readonly';
			$('subjectNumber')[i].value = "";
			$('queryImg')[i].style.display = 'none';
		}
		$('subjectNumber')[i].value = getUpFieldValue(getUpFieldsByFieldval(
				fieldMap.subjectNumber).eq(i)).value;
		$('companySelect')[i].value = companyMap[getUpFieldValue(getUpFieldsByFieldval(
				fieldMap.companySelect).eq(i)).value];
		$('typeSelect')[i].value = typeMap[getUpFieldValue(getUpFieldsByFieldval(
				fieldMap.typeSelect).eq(i)).value];
		$('remark')[i].value = getUpFieldValue(getUpFieldsByFieldval(
				fieldMap.remark).eq(i)).value;
		$('code')[i].value = getUpFieldValue(getUpFieldsByFieldval(
				fieldMap.code).eq(i)).value;
	}

	document.getElementById("ok_button").onclick = onOKButtonClick;
	document.getElementById("querySubjectNameButton").onclick = document
			.getElementById("querySubjectCodeButton").onclick = function() {
		querySubjectInfo(this);
	};

	// });

};
